import useUserStore from '@/stores/userStore';
import { Button } from 'antd';
import React, { useEffect, useState } from 'react';

interface Props {
  accessKey: string;
  actionType?: string;
  text?: string;
  link?: string | undefined;
}

const MButton: React.FC<Props> = (props) => {
  const { accessKey, actionType, text, link } = props;

  const [roles, setRoles] = useState<string[]>();
  const [flag, setFlag] = useState<boolean>(false);
  const [userInfo, setUserInfo] = useState<API.LoginUser>();
  const [layout, setLayout] = useState<React.ReactNode>('');

  function actionLayout() {
    switch (actionType) {
      case 'view':
        setLayout(
          <Button type={link ? 'link' : 'primary'} href={link}>
            {text ? text : '查看'}
          </Button>,
        );
        break;
      case 'delete':
        setLayout(<Button danger={true}>{text ? text : '删除'}</Button>);
        break;
      case 'edit':
        setLayout(<Button type="dashed">{text ? text : '编辑'}</Button>);
        break;
      default:
        setLayout(<Button>{text}</Button>);
        break;
    }
  }

  useEffect(() => {
    let useUserStore1 = new useUserStore();
    let userInfo1 = useUserStore1.getUserInfo();
    let roles1 = userInfo1?.roles;
    if (roles1?.indexOf(accessKey) > -1) {
      setFlag(true);
      actionLayout();
    } else {
      setFlag(false);
    }
    setRoles(roles1);
    setUserInfo(userInfo1);
  });

  return layout;
};
export default MButton;
